import React, { useState, useEffect } from 'react';
import styles from './RightPannel.less';
import classNames from 'classnames';
import { connect } from 'umi';
import { EventItemType } from '../dict';
import { Form, Tabs, Input, Select, Checkbox, Radio } from 'antd';
import { useCanvasContext } from '../CanvasContext';
import * as api from '../service';
import { PlusOutlined, MinusOutlined } from '@ant-design/icons';
import { cloneDeep } from '@antv/x6/lib/util/object/object';
import { value } from 'lodash-es';
import { set } from 'lodash';
import { async } from '@antv/x6/lib/registry/marker/main';

const { TabPane } = Tabs;

const dataTconditions = require('@/assets/styles/dataTconditions.png');
const tConditions = require('@/assets/styles/tConditions.png');

function NodeView(props) {
  const { wfeditor, dispatch } = props;
  const canvasContext = useCanvasContext();
  const [form] = Form.useForm();
  const { selectedId, selectedObj, formList } = wfeditor;

  const [basicFormFields, setBasicFormFields] = useState([
    { name: ['desc'], value: '' },
    { name: ['editType'], value: 'edit' },
    { name: ['meetType'], value: 'one' },
  ]);
  const [currentType, setCurrentType] = useState('edit');
  const [currentMeet, setCurrentMeet] = useState('one');
  const [currentCondition, setCurrentCondition] = useState('0');
  const [fieldList, setFieldList] = useState([]);
  const [wayList, setWayList] = useState([
    {
      name: '大于',
      value: '>',
    },
    {
      name: '大于等于',
      value: '>=',
    },
    {
      name: '等于',
      value: '==',
    },
    {
      name: '小于等于',
      value: '<=',
    },
    {
      name: '小于',
      value: '<',
    },
  ]);
  const [conditionList, setConditionList] = useState([
    // {
    //   id: 1,
    //   page: null,
    //   field: null,
    //   conditions: null,
    //   content: '',
    //   fieldList: [],
    // },
    // {
    //   id: 2,
    //   page: null,
    //   field: null,
    //   conditions: null,
    //   content: '',
    //   fieldList: [],
    // },
    // {
    //   id: 3,
    //   page: null,
    //   field: null,
    //   conditions: null,
    //   content: '',
    //   fieldList: [],
    // },
  ]);

  const versionList = [
    { id: 1, value: 'edit', text: '使用自定义流转条件' },
    { id: 2, value: 'else', text: '使用Else条件' },
  ];

  const onBasicValuesChange = (changedValues, allValues) => {
    const keys = Object.keys(changedValues);
    if (keys.length < 1) return;
    const key = keys[0];
    const value = changedValues[key];
    switch (key) {
      case 'editType':
        setCurrentType(value);
        updateNode(key, value);
        break;
      default:
        updateNode(key, value);
        break;
    }
  };

  const updateNode = (key, value) => {
    dispatch({
      type: 'wfeditor/updateCellEffect',
      payload: { id: selectedId, prop: key, value },
    });
    canvasContext.updateGraphProps(selectedId, 'data', {
      [key]: value,
    });
  };

  useEffect(() => {
    if (selectedId) intEdgeView();
  }, [selectedId]);

  const intEdgeView = () => {
    wfeditor.propList.length &&
      wfeditor.propList.forEach((item) => {
        if (item.id == selectedId) {
          setBasicFormFields([
            { name: ['desc'], value: item.data.desc },
            { name: ['editType'], value: item.data.editType },
            { name: ['meetType'], value: item.data.meetType },
          ]);
          setCurrentType(item.data.editType);
          setCurrentMeet(item.data.meetType);
          if (item.data.conditionList && item.data.conditionList.length) {
            item.data.conditionList.forEach((item, index) => {
              if (item.page) {
                let currentItem;
                formList.forEach((formItem) => {
                  if (formItem.pagePath == item.page) {
                    currentItem = formItem;
                  }
                });
                if (currentItem) {
                  const params = {
                    pageId: currentItem.id,
                  };
                  api.getTableColList(params).then((res) => {
                    if (res && res.code == '200') {
                      item.fieldList = res.data;
                    }
                  });
                } else {
                  item.fieldList = [];
                }
              }
            });
            setConditionList(item.data.conditionList);
          } else {
            setConditionList(item.data.conditionList);
          }
        }
      });
  };

  const addCondition = () => {
    let arr = cloneDeep(conditionList);
    arr.push({
      page: null,
      field: null,
      conditions: null,
      content: '',
      fieldList: [],
    });
    setConditionList(arr);
    updateNode('conditionList', arr);
    setCurrentCondition((arr.length - 1).toString());
  };
  const deleteCondition = () => {
    let arr = cloneDeep(conditionList);
    arr.splice(currentCondition, 1);
    setConditionList(arr);
    updateNode('conditionList', arr);
  };

  const selectPage = (value) => {
    let arr = cloneDeep(conditionList);
    let currentItem;
    formList.forEach((item) => {
      if (item.pagePath == value) {
        currentItem = item;
      }
    });
    let params = {
      pageId: currentItem.id,
    };
    arr[parseInt(currentCondition)].page = currentItem.pagePath;
    api.getTableColList(params).then((r) => {
      if (r && r.code == '200') {
        arr[parseInt(currentCondition)].field = null;
        arr[parseInt(currentCondition)].fieldList = r.data;
        setConditionList(arr);
        updateNode('conditionList', arr);
      }
    });
  };

  const changeItem = (value, key) => {
    let arr = cloneDeep(conditionList);
    if (key == 'content') {
      arr[parseInt(currentCondition)][key] = value.target.value;
    } else {
      arr[parseInt(currentCondition)][key] = value;
    }
    setConditionList(arr);
    updateNode('conditionList', arr);
    if (key == 'conditions' || key == 'content') {
      let timer = setTimeout(() => {
        updateEquation(arr);
      }, 100);
    }
  };

  const updateEquation = (arr) => {
    let equation = {
      componentColumns: [],
      conditionExpression: '',
    };

    arr.forEach((item) => {
      item.fieldList.forEach((fieldItem) => {
        if (item.field == fieldItem.columnId) {
          equation.componentColumns.push(fieldItem);
        }
      });
    });
    let startString = '${';
    let endString = '}';
    let or = '||';
    let and = '&&';
    let addExpression = '';
    arr.forEach((item, index) => {
      if (currentMeet == 'one') {
        if (index == arr.length - 1) {
          addExpression += equation.componentColumns[index]
            ? equation.componentColumns[index].javaField +
              ' ' +
              item.conditions +
              ' ' +
              item.content
            : '';
        } else {
          addExpression += equation.componentColumns[index]
            ? equation.componentColumns[index].javaField +
              ' ' +
              item.conditions +
              ' ' +
              item.content +
              ' ' +
              or +
              ' '
            : '';
        }
      } else {
        if (index == arr.length - 1) {
          addExpression += equation.componentColumns[index]
            ? equation.componentColumns[index].javaField +
              ' ' +
              item.conditions +
              ' ' +
              item.content
            : '';
        } else {
          addExpression += equation.componentColumns[index]
            ? equation.componentColumns[index].javaField +
              ' ' +
              item.conditions +
              ' ' +
              item.content +
              ' ' +
              and +
              ' '
            : '';
        }
      }
    });
    equation.conditionExpression = startString + addExpression + endString;
    updateNode('equation', equation);
  };

  const changeCurrent = (value) => {
    setCurrentCondition(value);
  };

  const changeMeet = (value) => {
    setCurrentMeet(value.target.value);
    updateEquation(conditionList);
  };

  return (
    <div>
      <div className={classNames(styles.block, styles.basicInfo)}>
        <Form
          fields={basicFormFields}
          name="basic"
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          onValuesChange={onBasicValuesChange}
        >
          <div className={styles.secTitle}>
            <img src={dataTconditions} />
            <span>数据流转条件</span>
          </div>
          <Form.Item
            wrapperCol={{ span: 24 }}
            label=""
            name="editType"
            rules={[{ required: false, message: '请选择' }]}
          >
            <Select style={{ width: '100%' }}>
              {versionList.length > 0 &&
                versionList.map((item) => (
                  <Option key={item.id} value={item.value}>
                    {item.text}
                  </Option>
                ))}
            </Select>
          </Form.Item>

          <div className={styles.explain}>
            <div>
              当数据满足流转条件时，进入这条连接线下的节点；不添加流转条件时，所有数据都会进入这条连接线下的节点
            </div>
          </div>
          {currentType == 'edit' ? (
            <div className={classNames(styles.block, styles.conditions)}>
              <div className={styles.secTitle}>
                <img src={tConditions} />
                <span>流转条件</span>
              </div>

              <Form.Item
                label="满足条件"
                name="meetType"
                rules={[{ required: false, message: '请选择满足条件' }]}
              >
                <Radio.Group onChange={changeMeet} style={{ width: '100%' }}>
                  <Radio value="one">任一条件</Radio>
                  <Radio value="all">所有条件</Radio>
                </Radio.Group>
              </Form.Item>
            </div>
          ) : null}
        </Form>
      </div>
      {currentType == 'edit' ? (
        <div className={classNames(styles.block, styles.conditionsList)}>
          <div className={styles.secTitle}>
            <span>流转条件列表</span>
            <div>
              <PlusOutlined onClick={addCondition} />
              <MinusOutlined onClick={deleteCondition} />
            </div>
          </div>
          <Tabs activeKey={currentCondition} onChange={changeCurrent}>
            {conditionList.length &&
              conditionList.map((item, index) => {
                return (
                  <TabPane tab={'条件' + (index + 1)} key={index.toString()}>
                    <div className={styles.content}>
                      <Select
                        value={item.page}
                        onChange={selectPage}
                        placeholder="请选择页面"
                        style={{ width: '100%' }}
                      >
                        {formList.length > 0 &&
                          formList.map((item) => (
                            <Option key={item.id} value={item.pagePath}>
                              {item.pageNameCh}
                            </Option>
                          ))}
                      </Select>
                      <Select
                        onChange={(e) => changeItem(e, 'field')}
                        value={item.field}
                        placeholder="请选择字段"
                        style={{ width: '100%' }}
                      >
                        {item.fieldList.length > 0 &&
                          item.fieldList.map((item) => (
                            <Option key={item.columnId} value={item.columnId}>
                              {item.tableName + '.' + item.columnName}
                            </Option>
                          ))}
                      </Select>
                      <Select
                        value={item.conditions}
                        onChange={(e) => changeItem(e, 'conditions')}
                        placeholder="请选择条件"
                        style={{ width: '100%' }}
                      >
                        {wayList.length > 0 &&
                          wayList.map((item) => (
                            <Option key={item.value} value={item.value}>
                              {item.name}
                            </Option>
                          ))}
                      </Select>
                      <Input
                        value={item.content}
                        onChange={(e) => changeItem(e, 'content')}
                        placeholder="请输入变量值"
                      />
                    </div>
                  </TabPane>
                );
              })}
          </Tabs>
        </div>
      ) : null}
    </div>
  );
}

export default connect(({ wfeditor }) => ({ wfeditor }))(NodeView);
